<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Support\Facades\Session;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

    public function weibo()
    {
        return \Socialite::with('weibo')->redirect();
        // return \Socialite::with('weibo')->scopes(array('email'))->redirect();
    }

    public function callback()
    {
        $oauthUser = \Socialite::with('weibo')->user();

        $weiboUser['Id'] = $oauthUser->getId();
        $weiboUser['Nickname'] = $oauthUser->getNickname();
        $weiboUser['Name'] = $oauthUser->getName();
        $weiboUser['Email'] = $oauthUser->getEmail();
        $weiboUser['Avatar'] = $oauthUser->getAvatar();

        if(!$this->weiboCallback($weiboUser))
            return redirect()->action();

        return redirect('/');
    }

    public function weiboCallback($weibo)
    {
        $weiboUser = User::where('weibo_id', $weibo['Id'])->first();
        if($weiboUser) {
            Auth::login($weiboUser);
            return true;
        }
        else
            return false;
    }

    public function bindAccount($option)
    {
        return view('users.bind',compact('option'));
    }

    public function addAuthUser($weibo)
    {
        $user = User::create([
            'name' => $weibo['Nickname'],
            'email' => $weibo['Email']?$weibo['Email']:'test@mail.com',
            'avatar' => $weibo['Avatar'],
            'weibo_id' => $weibo['Id'],
            'password' => bcrypt($weibo['Nickname']),
        ]);
        Auth::login($user);
    }

    //后台登陆方法
    public function getLogin()
    {
        if (view()->exists('auth.authenticate')) {
            return view('auth.authenticate');
        }

        $builder = new CaptchaBuilder();
        $builder->build();
        Session::put('phrase', $builder->getPhrase());

        return view('auth.login')->with('captcha', $builder->inline());
    }

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required',
            'password'             => 'required',
            'captcha'              => 'required'
        ], [
            $this->loginUsername() . '.required' => '请输入邮箱或用户名称',
            'password.required'                  => '请输入用户密码',
            'captcha.required'                   => '请输入验证码'
        ]);

        if (Session::get('phrase') !== $request->get('captcha')) {
            return redirect()->back()->withErrors(array('captcha' => '验证码不正确'))->withInput();
        }

        if(Auth::attempt([
            'email'=>$request->get('email'),
            'password'=>$request->get('password'),
//            'is_conf'=>1,
        ]) || Auth::attempt([
                'name'=>$request->get('email'),
                'password'=>$request->get('password'),
//            'is_conf'=>1,
            ])){
//            if(Auth::user()->hasRole('admin'))
                return redirect('/admin');
//            else
//                return redirect('/');
        }
        \Session::flash('user_login_failed','密码不正确或者邮箱没验证');
        return redirect('/auth/login')->withErrors(array('email' => '密码不正确或者邮箱没验证'))->withInput();
    }

    public function getLogout()
    {

    }
}
